package com.joymart.protocol.service;

import com.joymart.common.system.IdGenerator;
import com.joymart.common.utils.DatetimeUtils;
import com.joymart.order.model.Order;
import com.joymart.protocol.model.Protocol;
import com.joymart.protocol.repo.ProtocolRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jdbc.core.JdbcAggregateTemplate;
import org.springframework.data.relational.core.query.Criteria;
import org.springframework.lang.Nullable;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;

import static com.joymart.common.utils.CollectionUtils.asList;
import static org.springframework.data.relational.core.query.Criteria.where;
import static org.springframework.data.relational.core.query.Query.query;

@Service
public class ProtocolService {

    @Autowired
    private IdGenerator idGenerator;

    @Autowired
    private JdbcAggregateTemplate jdbcAggregateTemplate;

    @Autowired
    private ProtocolRepository protocolRepository;

    @Nullable
    public Protocol getLatestProtocol(String type) {
        return protocolRepository.findLatestByType(type);
    }

    @Nullable
    public Protocol findById(String id) {
        return protocolRepository.findById(id).orElse(null);
    }

    public Page<Protocol> searchProtocols(String type, Pageable pageable) {
        Criteria criteria = Criteria.empty();
        if(StringUtils.hasText(type)){
            criteria = criteria.and(where("type").is(type));
        }
        long count = jdbcAggregateTemplate.count(query(criteria), Protocol.class);
        if(count == 0){
            return Page.empty();
        }else {
            List<Protocol> content = asList(jdbcAggregateTemplate.findAll(query(criteria)
                    .limit(pageable.getPageSize()).offset(pageable.getOffset())
                    .sort(Sort.by(Sort.Direction.DESC, "createdAt")), Protocol.class));
            return new PageImpl<>(content, pageable , count);
        }
    }


    public void create(String type, String title, String content) {
        Protocol protocol = new Protocol();
        protocol.setId(idGenerator.next());
        protocol.setType(type);
        protocol.setTitle(title);
        protocol.setContent(content);
        protocol.setCreatedAt(DatetimeUtils.now());
        jdbcAggregateTemplate.insert(protocol);
    }
}
